package com.lwx.smipleemps.common.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtils {
    private static SessionFactory sessionFactory;
    private static ThreadLocal<Session> threadLocal =new ThreadLocal<>();
    static {
        Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
        ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }
    public static Session getSession(){
        Session session =threadLocal.get();
        if (session ==null){
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }
    /**
     * 开启
     */
    public static  void beginSessionTransaction(){
        Session session =threadLocal.get();
        if (session!=null){
            session.beginTransaction();
        }
    }
    /**
     * 关闭和提交
     */
    public static  void commitAndcloseSession(){
        Session session =threadLocal.get();
        if (session!=null){
            if (!session.getTransaction().wasCommitted()){
                session.getTransaction().commit();
            }
        }
        closeSession();
    }

    /**
     * 只关闭
     */
    public static  void closeSession(){
        Session session =threadLocal.get();
        if (session!=null){
            session.close();
            threadLocal.set(null);
        }
    }

    public static void main(String[] args) {
        System.out.println(HibernateUtils.getSession().hashCode());
        System.out.println(HibernateUtils.getSession().hashCode());
    }
}
